package com.mallcloud.mall.admin.handler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mallcloud.mall.admin.api.dto.UserInfo;
import com.mallcloud.mall.admin.api.entity.SysUser;
import com.mallcloud.mall.admin.service.SysUserService;
import com.mallcloud.mall.app.service.AppWxApiService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 微信小程序
 */
@Slf4j
@Component("MINI")
@AllArgsConstructor
public class MiniAppLoginHandler extends AbstractLoginHandler {

	private final SysUserService sysUserService;

	private final AppWxApiService wxApiService;

	/**
	 * 小程序登录传入code
	 * <p>
	 * 通过code 调用qq 获取唯一标识
	 *
	 * @param code
	 * @return openid
	 */
	@Override
	public String identify(String code) {
		return wxApiService.jsCodeToSession(code);
	}

	/**
	 * openId 获取用户信息
	 *
	 * @param openId
	 * @return
	 */
	@Override
	public UserInfo info(String openId) {
		SysUser user = sysUserService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getMiniOpenid, openId));

		if (user == null) {
			log.info("微信小程序openId[{}]尚未注册，自动注册...", openId);
			//创建微信小程序访客
			sysUserService.registerMallUser(openId);
			user = sysUserService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getMiniOpenid, openId));
		}
		return sysUserService.findUserInfo(user);
	}

	/**
	 * 绑定逻辑
	 *
	 * @param user     用户实体
	 * @param identify 渠道返回唯一标识
	 * @return
	 */
	@Override
	public Boolean bind(SysUser user, String identify) {
		user.setMiniOpenid(identify);
		sysUserService.updateById(user);
		return true;
	}

	/**
	 * 绑定逻辑
	 *
	 * @param user     用户实体
	 * @param phone 手机号
	 * @return
	 */
	@Override
	public Boolean bindPhone(SysUser user, String phone) {
		user.setPhone(phone);
		sysUserService.updateById(user);
		return true;
	}

	/**
	 * 绑定逻辑
	 *
	 * @param user     用户实体
	 * @param cardNo mall卡号
	 * @return
	 */
	@Override
	public Boolean bindCardNo(SysUser user, String cardNo) {
		user.setCardNo(cardNo);
		sysUserService.updateById(user);
		return true;
	}

}
